<script setup lang="ts">
import { ElButton } from 'element-plus';
import { ref, watch } from 'vue';
import { $t } from '@vben/locales';

const num = 90;
const count = ref<number>(num);
const CODE = 'getCode';
const isCounting = ref<boolean>(false);
const porps = defineProps({
  authCode: { type: String, default: "" },
  codeName: { type: String, default: $t('login.verificationCode') }
})

const emit = defineEmits([CODE]);
let timer: any = null;
const startCountdown = () => {
  if (isCounting.value) return;
  isCounting.value = true;
  timer = setInterval(() => {
    count.value--;
    if (count.value <= 0) {
      clearInterval(timer);
      isCounting.value = false;
      count.value = num;
    }
  }, 1000);
};

watch(() => porps.codeName, (newVal) => {
  clearInterval(timer);
  count.value = num;
  isCounting.value = false;
})

const handleClick = () => {
  clearInterval(timer);
  emit(CODE, startCountdown);
};

const resetCountdown = () => {
  clearInterval(timer);
  count.value = num;
  isCounting.value = false;
}

// 抛出 count 数据让外部可以获取
defineExpose({
  count,
  isCounting,
  resetCountdown
});

</script>
<template>
  <el-button type="primary" :disabled="isCounting" @click="handleClick" :class="{ 'btn': !!authCode }"
    style="background-color">
    {{ isCounting ? `${count}s 后重试` : codeName }}
  </el-button>
</template>
<style lang="less" scoped>
.btn {
  color: var(--el-color-primary) !important;
}
</style>
